package com.sptpc.demo.service.impl;

import com.sptpc.demo.model.Category;
import com.sptpc.demo.model.Drink;
import com.sptpc.demo.repository.CategoryRepository;
import com.sptpc.demo.repository.DrinkRepository;
import com.sptpc.demo.service.IDrinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DrinkJpaService implements IDrinkService {
    @Autowired
    private DrinkRepository drinkRepository;
    @Autowired
    public CategoryRepository categoryRepository;

    @Override
    public Page<Drink> getAllDrinks(PageRequest pageRequest) {

        return drinkRepository.findAll(pageRequest);
    }

    @Override
    public void addNewDrink(Drink drink, Integer categoryID) {
     //   1.通过categoryID查询category
        Category category= categoryRepository.findById(categoryID).orElse(null);
     //   2.将category设置给drink
        drink.setCategory(category);

        drinkRepository.save(drink);
    }

    @Override
    public Drink getDrinkById(Integer id) {
//        1.
//        Optional<Drink> optional= drinkRepository.findById(id);
//        if (optional.isPresent()) {
//            return optional.get();
//        }
//        return null;
//        2.
        return drinkRepository.findById(id).orElse(null);
    }

    @Override
    public void updateDrink(Drink drink) {
        drinkRepository.save(drink);
    }

    @Override
    public void deleteDrinkById(Integer id) {
        drinkRepository.deleteById(id);
    }


}
